﻿using System.Collections.Generic;
using System;
using System.Text;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;

namespace commonV2
{
    //From http://social.msdn.microsoft.com/Forums/en/winforms/thread/58cd891d-e7b8-45e2-9401-2b2f03c8bd97
    public class PleaseWait : IDisposable
    {
        private Form mSplash=null;
        private Point mLocation = new Point();

        public PleaseWait()
        {
            Init(new Point(), null);
        }
        public PleaseWait(Point location)
        {
            Init(location, null);
        }
        public PleaseWait(forms.baseSlashForm form)
        {
            Init( new Point(), form);
        }
        public PleaseWait(Point location, forms.baseSlashForm form)
        {
            Init(location, form);
        }
        protected virtual forms.baseSlashForm DefaultSplashForm()
        {
            return new forms.baseSlashForm();
        }

        private void Init(Point location, forms.baseSlashForm form)
        {
            mLocation = location;
            mSplash = (form == null ? DefaultSplashForm() : form);
            Thread t = new Thread(new ThreadStart(workerThread));
            t.IsBackground = true;
            t.SetApartmentState(ApartmentState.STA);
            t.Start();
        }

        public void Dispose()
        {
            if (mSplash == null || mSplash.IsDisposed) return;
            mSplash.Invoke(new MethodInvoker(stopThread));
        }
        private void stopThread()
        {
            if (mSplash == null) return;
            mSplash.Close();
        }
        private void workerThread()
        {
            if (mSplash == null || mSplash.IsDisposed) return;
            mSplash.Location = mLocation;
            mSplash.TopMost = true;
            Application.Run(mSplash);
        }
    }
}